package com.b.service.impl;

import com.b.dao.DynamicCommentMapper;
import com.b.dao.DynamicMapper;
import com.b.domain.Danmu;
import com.b.domain.Dynamic;
import com.b.domain.DynamicComment;
import com.b.domain.User;
import com.b.repository.DynamicCommentRepository;
import com.b.repository.DynamicRepository;
import com.b.repository.UserRepository;
import com.b.service.DynamicCommentService;
import com.b.vo.CommentMessage;
import com.b.vo.DynamicCommentVo;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DynamicCommentServiceImpl implements DynamicCommentService {
    @Resource
    private DynamicCommentRepository dynamicCommentRepository;
    @Resource
    private DynamicCommentMapper dynamicCommentMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private DynamicRepository dynamicRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<DynamicCommentVo> findByDynamic(Integer dynamicId) {
        // 查询该动态下的所有评论（包括回复）
        List<DynamicComment> comments = dynamicCommentRepository.findByDynamicId(dynamicId);

        // 转换为VO
        return convertToVoList(comments);
    }

    @Override
    public List<DynamicCommentVo> findRepliesByParentId(Integer parentId) {
        // 查询直接回复
        List<DynamicComment> replies = dynamicCommentRepository.findByParentId(parentId);
        return convertToVoList(replies);
    }

    @Override
    public List<DynamicCommentVo> findCommentChain(Integer rootCommentId) {
        // 1. 找到根评论
        Optional<DynamicComment> rootOpt = dynamicCommentRepository.findById(rootCommentId);
        if (!rootOpt.isPresent()) {
            return Collections.emptyList();
        }

        DynamicComment root = rootOpt.get();
        // 2. 获取该动态下的所有评论
        List<DynamicComment> allComments = dynamicCommentRepository.findByDynamicId(root.getDynamicId());

        // 3. 构建评论树
        Map<Integer, List<DynamicComment>> commentTree = new HashMap<>();
        for (DynamicComment comment : allComments) {
            commentTree.computeIfAbsent(comment.getParentId(), k -> new ArrayList<>()).add(comment);
        }

        // 4. 深度优先遍历构建对话链
        List<DynamicComment> chain = new ArrayList<>();
        buildCommentChain(root, commentTree, chain);

        return convertToVoList(chain);
    }

    private void buildCommentChain(DynamicComment comment,
                                   Map<Integer, List<DynamicComment>> commentTree,
                                   List<DynamicComment> chain) {
        chain.add(comment);
        List<DynamicComment> replies = commentTree.get(comment.getId());
        if (replies != null) {
            for (DynamicComment reply : replies) {
                buildCommentChain(reply, commentTree, chain);
            }
        }
    }

    private List<DynamicCommentVo> convertToVoList(List<DynamicComment> comments) {
        // 获取所有用户ID
        Set<Integer> userIds = comments.stream()
                .map(DynamicComment::getUserId)
                .collect(Collectors.toSet());

        // 批量查询用户信息
        Map<Integer, User> userMap = userRepository.findAllByIdIn(new ArrayList<>(userIds))
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        // 转换为VO
        return comments.stream().map(comment -> {
            User user = userMap.get(comment.getUserId());
            DynamicCommentVo  vo=new DynamicCommentVo();
            vo.setId(comment.getId());
            vo.setDynamicId(comment.getDynamicId());
            vo.setParentId(comment.getParentId());
            vo.setUserId(comment.getUserId());
            vo.setContent(comment.getContent());
            vo.setNickname(user.getNickname());
            vo.setAvatar(user.getAvatar());
            vo.setCreatedAt(comment.getCreatedAt());
            vo.setLikeCount(comment.getLikeCount());
            vo.setReplyCount(comment.getReplyCount());
            vo.setIsTop(comment.getIsTop());
            return vo;
        }).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void addComment(DynamicComment comment) {
        // 设置默认值
        comment.setCreatedAt(new Date());
        comment.setLikeCount(0);
        comment.setReplyCount(0);
        comment.setIsTop(0);
        // 1. 保存评论到MySQL
        dynamicCommentMapper.insert(comment);
        //2.更新elasticsearch的评论
        dynamicCommentRepository.save(comment);
        //3.获取数据库中的评论的id
        Integer commentId = comment.getId();
        // 4. 构造消息对象
        CommentMessage message = new CommentMessage();
        message.setId(commentId);
        message.setDynamicId(comment.getDynamicId());
        message.setParentId(comment.getParentId());

        // 5. 发送消息到队列
        rabbitTemplate.convertAndSend("comment", message);
    }

    @Override
    public void refresh(CommentMessage message) {
        rabbitTemplate.convertAndSend("comment", message);
    }

    @Override
    public List<DynamicComment> getAll() {
        return dynamicCommentMapper.getAll();
    }

    @Override
    public boolean importAll() {
        dynamicCommentMapper.getAll().forEach(dynamicComment -> dynamicCommentRepository.save(dynamicComment));
        return true;
    }
}
